"""
/* Copyright 2018 The Enflame Tech Company. All Rights Reserved.

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

    http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
==============================================================================*/
"""
# !/usr/bin/python
# coding=utf-8

import time
import datetime
import os
import sys
import re
import logging
import logging.handlers


_PREFIX = ':::ENFLAME_DTULOG'
PATTERN = re.compile('[a-zA-Z0-9]+')

LOG_FILE = os.getenv('ENFLAME_DTU_LOG_FILE')

DTU_LOGGER = logging.getLogger('enflame_dtu_app')
DTU_LOGGER.setLevel(logging.INFO)
formatter = logging.Formatter("%(asctime)s - %(name)s - %(levelname)s - %(message)s")

if LOG_FILE:
    # _FILE_HANDLER = logging.FileHandler(LOG_FILE)
    _FILE_HANDLER = logging.handlers.RotatingFileHandler(LOG_FILE, maxBytes=50 * 1024 * 1024,
                                                        backupCount=10, encoding=None, delay=0)
    _FILE_HANDLER.setLevel(logging.INFO)
    _FILE_HANDLER.setFormatter(formatter)
    DTU_LOGGER.addHandler(_FILE_HANDLER)

_STREAM_HANDLER = logging.StreamHandler(stream=sys.stdout)
_STREAM_HANDLER.setLevel(logging.INFO)
_STREAM_HANDLER.setFormatter(formatter)
DTU_LOGGER.addHandler(_STREAM_HANDLER)

LOG_TEMPLATE = ':::DTU {:.3f} {}: {{"value": {}, "metadata": {}}}'


class DTUBase(object):
    def __init__(self):
        self.tips = "Enflame model test base"


class DTULogger(DTUBase):
    """DTU model test logger"""
    def __init__(self):
        DTUBase.__init__(self)
        self.logger = DTU_LOGGER

    def _now_as_str(self):
        """Returns the current time as a human readable string."""
        return datetime.datetime.now().strftime('%H:%M:%S.%f')

    def _current_time_ns(self):
        """Returns current nanoseconds since epoch."""
        return time.time() * 1000 * 1000 * 1000

    def _try_float(value):
        """Tries to convert a value to a float (otherwise returns the input)."""
        try:
            return float(value)
        except Exception:  # pylint:disable=broad-except
            return value

    def info(self, msg):
        self.logger.info(msg)

    def debug(self, msg):
        self.logger.debug(msg)

    def warn(self, msg):
        self.logger.warning(msg)

    def error(self, msg):
        self.logger.error(msg)
        if LOG_FILE:
            from utils.system_status import Summary
            self.logger.error(Summary.collection())
            from tensorflow.python.client import device_lib
            self.logger.error(device_lib.list_local_devices())

LOGGER = DTULogger()
